import React, { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import {
  Card,
  Typography,
  Button,
  TextField,
  Alert,
  Box,
  Paper,
  InputAdornment
} from '@mui/material';
import {
  Person,
  AdminPanelSettings,
  Search,
  Gavel
} from '@mui/icons-material';
import { userStorage } from '../../utils/api';
import { User } from '../../types';
import styles from './AdminReview.module.css';

const AdminApplicationsList: React.FC = () => {
  const navigate = useNavigate();
  const [currentUser, setCurrentUser] = useState<User | null>(null);
  const [userId, setUserId] = useState('');
  const [error, setError] = useState<string | null>(null);

  // 检查权限
  useEffect(() => {
    const userData = userStorage.get();
    setCurrentUser(userData);
    
    // 只有超级管理员可以访问
    if (!userData || userData.role !== 'SUPERADMIN') {
      navigate('/home');
      return;
    }
  }, [navigate]);

  // 处理审核
  const handleReview = () => {
    setError(null);
    
    if (!userId.trim()) {
      setError('请输入用户ID');
      return;
    }

    const userIdNum = parseInt(userId.trim());
    if (isNaN(userIdNum) || userIdNum <= 0) {
      setError('请输入有效的用户ID（正整数）');
      return;
    }

    navigate(`/admin/review/${userIdNum}`);
  };

  // 处理键盘事件
  const handleKeyPress = (event: React.KeyboardEvent) => {
    if (event.key === 'Enter') {
      handleReview();
    }
  };

  if (!currentUser || currentUser.role !== 'SUPERADMIN') {
    return (
      <div className={styles.container}>
        <Card className={styles.reviewCard}>
          <div className={styles.errorContainer}>
            <AdminPanelSettings className={styles.errorIcon} />
            <Typography variant="h5" className={styles.errorTitle}>
              权限不足
            </Typography>
            <Typography variant="body1" className={styles.errorMessage}>
              只有超级管理员可以访问此页面
            </Typography>
            <Button
              variant="contained"
              onClick={() => navigate('/home')}
              className={styles.backButton}
            >
              返回首页
            </Button>
          </div>
        </Card>
      </div>
    );
  }

  return (
    <div className={styles.container}>
      <Card className={styles.reviewCard}>
        {/* 页面标题 */}
        <div className={styles.header}>
          <Typography variant="h4" className={styles.title}>
            管理员申请审核
          </Typography>
          <Typography variant="body1" className={styles.subtitle}>
            输入申请人的用户ID进行审核
          </Typography>
        </div>

        {/* 说明卡片 */}
        <Paper sx={{ p: 3, mb: 3, bgcolor: 'info.light', color: 'info.contrastText' }}>
          <Box sx={{ display: 'flex', alignItems: 'center', gap: 2, mb: 2 }}>
            <AdminPanelSettings />
            <Typography variant="h6">
              管理员审核说明
            </Typography>
          </Box>
          <Typography variant="body2" sx={{ mb: 2 }}>
            • 当有用户申请成为管理员时，系统会发送邮件通知您
          </Typography>
          <Typography variant="body2" sx={{ mb: 2 }}>
            • 请从邮件中获取申请人的用户ID，然后在下方输入进行审核
          </Typography>
          <Typography variant="body2">
            • 您可以选择通过或拒绝申请，拒绝时需要提供拒绝原因
          </Typography>
        </Paper>

        {/* 用户ID输入 */}
        <Box sx={{ mb: 3 }}>
          <TextField
            fullWidth
            label="申请人用户ID"
            placeholder="请输入申请人的用户ID"
            value={userId}
            onChange={(e) => setUserId(e.target.value)}
            onKeyPress={handleKeyPress}
            variant="outlined"
            InputProps={{
              startAdornment: (
                <InputAdornment position="start">
                  <Person />
                </InputAdornment>
              ),
            }}
            helperText="请输入正整数，例如：123"
          />
        </Box>

        {/* 错误提示 */}
        {error && (
          <Alert severity="error" sx={{ mb: 3 }}>
            {error}
          </Alert>
        )}

        {/* 操作按钮 */}
        <Box sx={{ display: 'flex', gap: 2, justifyContent: 'center' }}>
          <Button
            variant="outlined"
            onClick={() => navigate('/home')}
          >
            返回首页
          </Button>
          <Button
            variant="contained"
            onClick={handleReview}
            startIcon={<Gavel />}
            disabled={!userId.trim()}
          >
            开始审核
          </Button>
        </Box>

        {/* 示例卡片 */}
        <Paper sx={{ p: 3, mt: 3, bgcolor: 'grey.50' }}>
          <Typography variant="h6" sx={{ mb: 2, display: 'flex', alignItems: 'center', gap: 1 }}>
            <Search />
            使用示例
          </Typography>
          <Typography variant="body2" color="text.secondary" sx={{ mb: 1 }}>
            1. 收到管理员申请邮件通知
          </Typography>
          <Typography variant="body2" color="text.secondary" sx={{ mb: 1 }}>
            2. 从邮件中找到申请人的用户ID（例如：123）
          </Typography>
          <Typography variant="body2" color="text.secondary" sx={{ mb: 1 }}>
            3. 在上方输入框中输入用户ID
          </Typography>
          <Typography variant="body2" color="text.secondary">
            4. 点击"开始审核"按钮进入审核页面
          </Typography>
        </Paper>
      </Card>
    </div>
  );
};

export default AdminApplicationsList; 